package net.dgg.dggcloud.service.jrcrm.service.pro;

import com.google.gson.Gson;
import net.dgg.dggcloud.core.idwork.KeyWorker;
import net.dgg.dggcloud.core.minidao.hibernate.dao.IGenericBaseCommonDao;
import net.dgg.dggcloud.core.util.ExcelTool;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.dao.pro.ProductChannelDao;
import net.dgg.dggcloud.service.jrcrm.entity.cms.TreeBook;
import net.dgg.dggcloud.service.jrcrm.entity.pro.Product;
import net.dgg.dggcloud.service.jrcrm.entity.pro.ProductChannel;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.cms.BillNumberRuleService;
import net.dgg.dggcloud.service.jrcrm.service.cms.TreeBookService;
import net.dgg.dggcloud.service.jrcrm.vo.ValidateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/9.
 */
@Service
public class ProductChannelService extends BaseService{
    @Autowired
    private ProductChannelDao productChannelDao;

    @Resource(name = "miniDaoHiberCommonDao")
    protected IGenericBaseCommonDao repository;

    @Autowired
    protected KeyWorker keyWorker;

    @Resource
    private BillNumberRuleService bs ;

    @Autowired
    private TreeBookService treeBookService;

    public List<Map> listProductChannelByCondition(Map map){
        return productChannelDao.listProductChannelByCondition(map);
    }
    public Long countPageByMap(Map map){
        return productChannelDao.countPageByMap(map);
    }

    public List<Map> listProductChannelPageByCondition(Map map){
        return productChannelDao.listProductChannelPageByCondition(map);
    }

    public ValidateResult deleteByIds(String[] ids){
        ValidateResult validateResult = new ValidateResult();

        try {
            if(null != ids && ids.length>0){
                for(String id : ids){
                    ProductChannel productChannel = repository.get(ProductChannel.class,Long.parseLong(id));
                    if(productChannel == null){
                        continue;
                    }
                    productChannel.setStatus(0); //删除标记
                    repository.saveOrUpdate(productChannel);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            validateResult.setSuccess(false);
            return validateResult;
        }

        validateResult.setSuccess(true);
        return validateResult;
    }

    public void saveOne(ProductChannel productChannel,User curUser){

        ValidateResult validateResult = validateChannel(productChannel);

        if(!validateResult.getSuccess()){
            throw new BizException(validateResult.getMsg(),0);
        }
//        productChannel.setId(keyWorker.nextId());
        //设置一级类别
        TreeBook treeBook = treeBookService.queryTreeBookParentByCode(productChannel.getCategory());
        if(treeBook != null){
            productChannel.setType(treeBook.getPcode());
        }

        try{
            productChannel.setSerialNum(bs.updateBillNumberByCode("QD"));
        }catch (BizException e){
            logger.error("获取产品渠道编号失败！" + e.getLocalizedMessage());
            throw new BizException("获取渠道编号失败",10001);
        }
        productChannel.setStatus(1); //标配为 未删除

        productChannel.setCreaterId(curUser.getId());
        productChannel.setCreaterName(curUser.getName() + curUser.getLoginName());
        productChannel.setCreaterOrgId(curUser.getDeptId());
        productChannel.setCreateTime(new Date());

        productChannel.setUpdaterId(curUser.getId());
        productChannel.setUpdaterName(curUser.getName() + curUser.getLoginName());
        productChannel.setUpdaterOrgId(curUser.getDeptId());
        productChannel.setUpdateTime(new Date());

        repository.save(productChannel);
    }

    public void updateOne(ProductChannel productChannel,User curUser){
        try {

            ValidateResult validateResult = validateChannel(productChannel);
            if(!validateResult.getSuccess()){
                throw new BizException(validateResult.getMsg(),0);
            }

//            ProductChannel oldPorductChannel = repository.get(ProductChannel.class,productChannel.getId());
//            oldPorductChannel.setName(productChannel.getName());
//
//
            //设置一级类别
            TreeBook treeBook = treeBookService.queryTreeBookParentByCode(productChannel.getCategory());
            if(treeBook != null){
                productChannel.setType(treeBook.getPcode());
            }

            productChannel.setUpdaterId(curUser.getId());
            productChannel.setUpdaterName(curUser.getName() + curUser.getLoginName());
            productChannel.setUpdaterOrgId(curUser.getDeptId());
            productChannel.setUpdateTime(new Date());
//
//            oldPorductChannel.setCategory(productChannel.getCategory());

            repository.saveOrUpdate(productChannel);
        }catch (BizException be){
            throw be;
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException("数据异常",0);
        }
    }

    public List<ProductChannel> getAllChannel(){
        List<ProductChannel> list = (List<ProductChannel>) repository.getSession().createQuery("From ProductChannel").list();
        return list;
    }



    private ValidateResult validateChannel(ProductChannel productChannel){
        ValidateResult validateResult = new ValidateResult();
        validateResult.setSuccess(true);
        if(productChannel == null){
            validateResult.setSuccess(false);
            validateResult.setMsg("数据为空！");
            return validateResult;
        }
        if(StringUtils.isBlank(productChannel.getCategory())){
            validateResult.setSuccess(false);
            validateResult.setMsg("请选择'所属类别'！");
            return validateResult;
        }
        if(StringUtils.isBlank(productChannel.getName())){
            validateResult.setSuccess(false);
            validateResult.setMsg("'渠道名'不能为空！");
            return validateResult;
        }
        if(StringUtils.isBlank(productChannel.getCooperationStatus())){
            validateResult.setSuccess(false);
            validateResult.setMsg("'合作状态'不能为空！");
            return validateResult;
        }
        if(productChannel.getFirstCooperationTime() != null && productChannel.getCooperationExpiration() != null){
            if(productChannel.getFirstCooperationTime().getTime() > productChannel.getCooperationExpiration().getTime()){
                validateResult.setSuccess(false);
                validateResult.setMsg("'首次日期'不能大于'到期时间'！");
                return validateResult;
            }
        }
        if(StringUtils.isBlank(productChannel.getApplyArea())){
            validateResult.setSuccess(false);
            validateResult.setMsg("请选择'适用区域'！");
            return validateResult;
        }


        return validateResult;
    }

    public ProductChannel getChannelById(Long id){

        ProductChannel channel = repository.get(ProductChannel.class,id);
        return channel;
    }

    /**
     * 批量修改删除状态
     * @param ids
     */
    public void batchDeleteByIds(Long[] ids){
        if(null != ids && ids.length > 0){
            for(Long currentId : ids){
                ProductChannel channel = repository.get(ProductChannel.class,currentId);
                channel.setStatus(0); //删除标志
                repository.saveOrUpdate(channel);
            }
        }
    }

    /**
     * 批量修改合作状态
     * @param ids
     * @param cooperationStatus
     */
    public void updateCooperationStatus(Long[] ids,String cooperationStatus){
        if(null != ids && ids.length > 0){
            for(Long currentId : ids){
                ProductChannel channel = repository.get(ProductChannel.class,currentId);
                channel.setCooperationStatus(cooperationStatus);
                repository.saveOrUpdate(channel);
            }
        }
    }
}
